import express from "express"
import path from "node:path"
import multer from "multer"

const uploadRouter = express.Router();

//设置上传目录、文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.resolve(process.cwd(), "./static"));
  },
  filename: function (req, file, cb) {
    const random = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, random + file.originalname.match(/\.[a-z]+$/g)?.[0]);
  },
});

const upload = multer({
  storage: storage,
});

//上传
uploadRouter.post("/upload", upload.single("file"), async function (req, res) {
  const result = {
    url: "/" + req.file.filename,
  };
  res.append("content-type", "application/json");
  res.send(JSON.stringify(result));
});

export default uploadRouter;
